/**
 * Created by Weizehua on 2017/2/20.
 */
import {HandlerClass, Handle, ParamType, Require} from "../Core/Dispatcher/Dispatcher";
import {Connection} from "typeorm";
import {isLogged} from "./UserHandler";
import {UserInfo} from "../UserInfo/UserInfo";
@HandlerClass()
export class SearchHandler {
    constructor(protected typeorm: Connection) {
    }

    @Handle('/user/search/id')
    @ParamType({
        id: Number
    })
    @Require(isLogged)
    async searchUserByIdHandler(param: any) {
        let id = param.id;
        let info = await this.typeorm.entityManager
            .findOne(UserInfo, {user: id});
        if (!info)
            return "用户不存在";
        return {
            success: true, user: {
                id: id,
                nickname: info.nickname,
                headUrl: info.headUrl,
            }
        }
    }

    @Handle('/user/search/name')
    @ParamType({
        name: String,
        limit: Number
    })
    @Require(isLogged)
    async searchUserByNameHandler(param: any) {
        let limit = Math.min(10, param.limit);
        let name = param.name;
        let infos = await this.typeorm.entityManager
            .find(UserInfo, {nickname: name});
        if (!infos)
            return "找不到任何符合条件的用户";
        let res = infos.map(v => ({id: v.id, nickname: v.nickname, headUrl: v.headUrl}));
        return {
            success: true, users: res
        }
    }
}
